package com.hwangrq;

import com.hwangrq.service.WorkService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author hwangrq
 */
public class ConsumerMain {

    public static void main(String[] args) throws Exception {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:consumer.xml");
        context.start();
        // 获取远程服务代理
        WorkService workService = (WorkService)context.getBean("workService");
        System.in.read();
        // 执行远程方法
//        String s = workService.methodA();
//        System.out.println("================" + s + "================");

        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 2000; i++) {
            Task a = new Task("A", workService);
            Task b = new Task("B", workService);
            Task c = new Task("C", workService);
            executorService.execute(a);
            executorService.execute(b);
            executorService.execute(c);
        }
    }

    static class Task implements Runnable {

        private String name;
        private WorkService workService;

        public Task(String name, WorkService workService) {
            this.name = name;
            this.workService = workService;
        }

        @Override
        public void run() {
            String s =null;
            int timeout = (int) (Math.random() * 100);
            switch (name) {
                case "A":
                    s = workService.methodA(timeout);
                    break;
                case "B":
                    s = workService.methodB(timeout);
                    break;
                case "C":
                    s = workService.methodC(timeout);
                    break;
                default:
                    throw new RuntimeException("workService 没有method" + name);
            }
//            System.out.println("=============== "+ s + "，花费时间：" + timeout +"ms ===============");

        }
    }
}
